import DTO.People;
import DTO.Student;
import DTO.userinfomation;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.json.Json;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet(urlPatterns = {"/login/dgut"})
public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // System.out.print("--------------------------------------------------------------!!!!!!!!!!------------------------------------------------------------------------");
        String string1 = null;
        String string2 = null;

        String token = req.getParameter("token");
        List<NameValuePair> form = new ArrayList<>();
        form.add(new BasicNameValuePair("token", token));
        form.add(new BasicNameValuePair("appid", "javaee"));
        form.add(new BasicNameValuePair("appsecret", "b3b52e43ccfd"));
        form.add(new BasicNameValuePair("userip", req.getLocalAddr()));
        HttpPost httppost_1 = new HttpPost("https://cas.dgut.edu.cn/ssoapi/v2/checkToken");//检查token
        UrlEncodedFormEntity uefEntity_1;
         // 创建默认的httpClient实例.
       try (CloseableHttpClient httpclient_1 = HttpClients.createDefault()) {
            uefEntity_1 = new UrlEncodedFormEntity(form, "UTF-8");
            httppost_1.setEntity(uefEntity_1);
            try (CloseableHttpResponse response_1 = httpclient_1.execute(httppost_1)) {
                HttpEntity entity_1 = response_1.getEntity();
                if (entity_1 != null) {
                    string1= EntityUtils.toString(entity_1, "UTF-8");
                }
            }
        }



        Jsonb json = JsonbBuilder.create();
        People people = json.fromJson(string1,People.class);

        String openid1=people.getOpenid();
        String access_token1=people.getAccess_token();
        List<NameValuePair> form1= new ArrayList<>();

        form1.add(new BasicNameValuePair("access_token", access_token1));
        form1.add(new BasicNameValuePair("openid", openid1));

        HttpPost httppost_2 = new HttpPost("https://cas.dgut.edu.cn/oauth/getUserInfo");//获取用户基本信息
        UrlEncodedFormEntity uefEntity_2;
        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpclient_2 = HttpClients.createDefault()) {
            uefEntity_2 = new UrlEncodedFormEntity(form1, "UTF-8");
            httppost_2.setEntity(uefEntity_2);
            try (CloseableHttpResponse response_2 = httpclient_2.execute(httppost_2)) {
                HttpEntity entity_2 = response_2.getEntity();
                if (entity_2 != null) {
                    string2= EntityUtils.toString(entity_2, "UTF-8");
                }
            }
        }
        Jsonb json_student=JsonbBuilder.create();
        Student student=json_student.fromJson(string2,Student.class);

        String string_check = null;
        int flag = 0;
        String img = "default.jpg";
        String username = null;
        String password = null;
        String phone = "null";
        HttpSession session=req.getSession(true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("login.txt")));
       // BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("login.txt")));

        while((string_check = reader.readLine()) != null)//循环比对莞工登录的账号与本地账户数据
        {
            Jsonb jsonb_user = JsonbBuilder.create();
            userinfomation user_check = jsonb_user.fromJson(string_check,userinfomation.class);
            if(user_check.getUsername().equals(student.getUsername())){//检查本地数据是否有这个人，如果有，就把他的信息封装起来
                flag = 1;//flag=1 有这个人，flag=0 没有这个人
                Map<String,String>user_map1 = new HashMap<>();
                user_map1.put("username",user_check.getUsername());
                user_map1.put("password",user_check.getPasswd());
                user_map1.put("phone",user_check.getPhone());
                user_map1.put("img",img);
                session.setAttribute("USER",user_map1);//把其信息打包进对应的session
                break;
            }
        }
        if(flag == 0){//没有这个人的操作
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("login.txt", true)));
            username = student.getUsername();
            password = "123456";
            phone = "未输入";

            Jsonb json2 = JsonbBuilder.create();
            userinfomation user_new = new userinfomation(username,password,phone,img);
            String string_new = json2.toJson(user_new);
            out.write(string_new);
            out.close();
            //写入成功
            Map<String,String>user_map2 = new HashMap<>();
            user_map2.put("username",username);
            user_map2.put("password",password);
            user_map2.put("phone",phone);
            user_map2.put("img",img);
            session.setAttribute("USER",user_map2);
        }

        //req.getSession().setAttribute("student",student);

        resp.sendRedirect("http://localhost:8080/user.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}






